package com.peng.leetcode.search;

/**
 * SearchRange1
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
 * <p>
 * Created on 2022/12/8
 *
 * @author lupeng
 */
public class SearchRange1 {

    public static void main(String[] args) {
        int[] nums = new int[] {5,7,7,8,8,10};
        int[] range = new SearchRange1().searchRange(nums, 8);
        System.out.println(range);
    }

    public int[] searchRange(int[] nums, int target) {
        int lower = lowerSearch(nums, target);
        if (lower == nums.length || nums[lower] != target) {
            return new int[] {-1, -1};
        }
        int high = lowerSearch(nums, target + 1) - 1;
        return new int[] {lower, high};
    }

    int lowerSearch(int[] arr, int target) {
        int l = 0, r = arr.length;
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (arr[mid] < target) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        return l;
    }
}
